﻿using KWT.DRG_DIP.API.Infrastructure;
using KWT.DRG_DIP.Common;
using KWT.DRG_DIP.DB;
using KWT.DRG_DIP.DO.System;
using KWT.DRG_DIP.DTO.Basic.Enum;
using KWT.DRG_DIP.PO.Basic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;
using System.Linq;

namespace KWT.DRG_DIP.API.Controllers.Basic
{
    /// <summary>
    /// 枚举字典管理
    /// </summary>
    [ApiExplorerSettings(GroupName = "basic")]
    public class EnumController : BasicControllerBase
    {
        public EFContext ef { get; set; }

        /// <summary>
        /// 添加或编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult AddOrUpdate(InAddOrUpdate dto)
        {
            if (string.IsNullOrWhiteSpace(dto.EnumID))
            {
                var _enum = _mapper.Map<Sys_Enum>(dto);
                _enum.EnumID = "EM" + snow_id.CreateId().ToString();
                if (ef.Set<Sys_Enum>().Any(x => x.Text == dto.Text && x.Group == dto.Group))
                {
                    return Fail("当前组已存在相同的文本");
                }
                ef.Add(_enum);
            }
            else
            {
                var _enum = ef.Find<Sys_Enum>(dto.EnumID);
                if (_enum == null)
                {
                    return Fail("未找到该项！");
                }
                _enum.Group = dto.Group;
                _enum.Text = dto.Text;
                _enum.Value = dto.Value;
                _enum.Desc = dto.Desc;
                _enum.UpdTime = DateTime.Now;
                ef.Attach(_enum);
            }
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="enumIDs"></param>
        /// <returns></returns>
        [HttpGet]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult Del([FromQuery] string[] enumIDs)
        {
            var flag = ef.Set<Sys_Enum>().Where(x => enumIDs.Contains(x.EnumID)).ExecuteDelete() > 0;
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 批量导入
        /// </summary>
        /// <param name="file">excel文件</param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<string>), 200)]
        public OutputResult Import(IFormFile file)
        {
            using var pkg = new ExcelPackage(file.OpenReadStream());
            var worksheet = pkg.Workbook.Worksheets[0];

            var list = worksheet.Dimension.ToCollectionWithMappings(row =>
            {
                var _enum = new Sys_Enum
                {
                    Group = row.GetValue<string>("组"),
                    Text = row.GetValue<string>("文本"),
                    Value = row.GetValue<string>("值"),
                    Desc = row.GetValue<string>("说明"),
                };
                return _enum;
            }, options => options.HeaderRow = 0);
            list.ForEach(x => x.EnumID = "EM" + snow_id.CreateId().ToString());
            ef.AddRange(list);
            var flag = ef.SaveChanges() > 0;
            return Output(flag, "操作成功", "操作失败");
        }

        /// <summary>
        /// 获得组数据
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult GetGroup([FromQuery] string name)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                var list = ef.Set<Sys_Enum>().Select(x => x.Group).Distinct().AsNoTracking().ToList();
                var result = list.Select(x => new { label = x, value = x });
                return Output(list.Count() > 0, "", "", result);
            }
            else
            {
                var list = ef.Set<Sys_Enum>().Where(x => EF.Functions.Like(x.Group, $"%{name}%")).Select(x => new { label = x.Group, value = x.Group }).AsNoTracking().ToList();
                var result = list.DistinctBy(x => x.label);
                return Output(list.Count() > 0, "", "", result);
            }
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost]
        [ProducesResponseType(typeof(Output<PageList<Sys_Enum>>), 200)]
        public OutputResult PageList(InPageList dto)
        {
            var q = ef.Set<Sys_Enum>().AsQueryable();
            if (!string.IsNullOrWhiteSpace(dto.GroupName))
            {
                q = q.Where(x => x.Group == dto.GroupName);
            }
            if (!string.IsNullOrWhiteSpace(dto.Text))
            {
                q = q.Where(x => EF.Functions.Like(x.Text, $"%{dto.Text}%"));
            }
            if (!string.IsNullOrWhiteSpace(dto.Value))
            {
                q = q.Where(x => x.Value == dto.Value);
            }
            int total = q.Count();
            var list = q.OrderByDescending(x => x.AddTime).ToPageList(dto.PageNo, dto.PageSize);
            return Output(list != null, "", "", new PageList<Sys_Enum>() { List = list, Total = total });
        }

        /// <summary>
        /// 根据组名称获得字典数据
        /// </summary>
        /// <param name="group"></param>
        /// <returns></returns>
        [HttpGet]
        public OutputResult Data([FromQuery] string group)
        {
            if (!string.IsNullOrEmpty(group))
            {
                var list = ef.Set<Sys_Enum>().Where(x => x.Group == group).Select(x => new { x.Value, label = x.Text }).AsNoTracking().ToList();
                return Output(list.Count > 0, "", "", list);
            }
            else
            {
                var list = ef.Set<Sys_Enum>().Select(x => new { x.Group, x.Value, label = x.Text }).AsNoTracking().ToList().ToLookup(x=>x.Group).Select(x=>new {group=x.Key,data=x });
                return Output(list!=null, "", "", list);
            }
        }
    }
}
